<script lang="ts" setup>
import { createVNode, onMounted, ref } from 'vue';

import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import {
  Button,
  Divider,
  Input,
  message,
  Modal,
  Select,
  SelectOption,
} from 'ant-design-vue';

import { addMessageList, deleteMessageList, getMessageList } from '#/api';
import { BASE_ICON_URL } from '#/config';

const formData = ref({
  noticeType: 2, // 消息类型
  noticeContent: '', // 消息内容
});
interface IMessage {
  id: number;
  noticeType: number;
  noticeContent: string;
}
const list = ref<IMessage[]>([]);
// 最大添加限制
const maxLimit = ref(6);
// 添加按钮的loading
const addLoading = ref(false);

// 回去消息列表
const getList = async () => {
  try {
    const { data } = await getMessageList();
    list.value = data || [];
  } catch (error) {
    console.error('获取消息列表失败：', error);
  }
};
// 添加消息通知
const submit = async () => {
  try {
    // 判断是否超过添加限制
    if (list.value?.length >= maxLimit.value) return;
    addLoading.value = true;
    await addMessageList(formData.value);
    message.success('添加成功');
    formData.value.noticeContent = '';
    formData.value.noticeType = 2;
    await getList();
    addLoading.value = false;
  } catch (error) {
    addLoading.value = false;
    console.error('添加消息失败：', error);
  }
};

// 删除事件
const handleDelete = (id: number) => {
  const messageId = id;
  Modal.confirm({
    title: '删除提示',
    icon: createVNode(ExclamationCircleOutlined),
    content: '确认删除此消息通知吗？',
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        if (!messageId) return;
        await deleteMessageList({ id: messageId });
        message.success('删除成功');
        await getList();
      } catch (error) {
        console.error('删除消息失败:', error);
      }
    },
  });
};

onMounted(() => {
  getList();
});
</script>

<template>
  <div class="card-box mb-3 w-full rounded-md">
    <div class="px-4 pb-4">
      <div class="flex items-center justify-between py-3">
        <div class="text-xl font-bold">首页通知</div>
      </div>
      <div class="flex flex-wrap items-center">
        <div class="mb-2 mr-3">
          <Select
            v-model:value="formData.noticeType"
            :disabled="list.length >= maxLimit"
            size="large"
            style="width: 100px"
          >
            <SelectOption :value="1">优惠</SelectOption>
            <SelectOption :value="2">活动</SelectOption>
          </Select>
        </div>
        <div class="mb-2 mr-3">
          <Input
            v-model:value="formData.noticeContent"
            :disabled="list.length >= maxLimit"
            :maxlength="40"
            class="flex h-[40px] w-[360px] items-center overflow-hidden text-sm"
            placeholder="请输入消息内容"
            show-count
            size="large"
          />
        </div>
        <Button
          :disabled="
            formData.noticeContent === '' ||
            !formData.noticeType ||
            list.length >= maxLimit
          "
          :loading="addLoading"
          class="mb-2 flex h-auto items-center px-5 py-2"
          type="primary"
          @click="submit"
        >
          添加
        </Button>
      </div>
      <p class="opacity-60">
        添加的消息通知将在小程序首页的消息滚动中展示<span v-if="maxLimit > 0">
          (最多添加{{ maxLimit }}条)
        </span>
      </p>
      <div class="mb-3 mt-2 text-lg">消息通知列表</div>
      <ul v-if="list.length > 0" class="max-h-[410px] overflow-y-auto">
        <li v-for="item in list" :key="item.id">
          <div class="flex flex-wrap">
            <div class="h-auto w-[50px]">
              {{ item.noticeType === 1 ? '优惠' : '活动' }}
            </div>
            <div class="h-auto flex-1">{{ item.noticeContent || '' }}</div>
            <Button
              class="mx-2 h-auto p-0"
              type="link"
              @click="handleDelete(item.id)"
            >
              删除
            </Button>
          </div>
          <Divider class="my-3" />
        </li>
      </ul>
      <div
        v-else
        class="align-center flex flex-col items-center justify-center"
      >
        <img :src="`${BASE_ICON_URL}no-data.png`" class="h-auto w-[160px]" />
        <p class="mt-1 text-gray-400">暂无消息通知,快去添加吧~</p>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.icon {
  color: hsl(var(--primary));
}

.light {
  color: hsl(var(--card-foreground));
}

:deep(.ant-select-selection-item) {
  font-size: 14px;
}
</style>
